import java.awt.Cursor;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class mailRemoverGUI extends JFrame {
	private final String VERSION = "0.7";
	private Pop3 mailClient;
	private int mailCount;
	private int delMail;
	private boolean getInput = true;

	// GUI Components
	private mailRemoverGUI mrGUI;
	private JPanel northPanel;
	private JLabel hostLabel, usernameLabel, passwordLabel;
	private JTextField hostTextField, userTextField;
	private JPasswordField userPasswordField;
	private JButton connectButton;
	private JTextArea clientTextArea;
	private JScrollPane scrollArea;
	private ProgressMonitor m_progress;

	private class connectPressed implements ActionListener {
		public void actionPerformed(ActionEvent ae) {
			// Clear previous server messages.
			clientTextArea.setText("");

			if((hostTextField.getText().length() > 0) &&
					(userTextField.getText().length() > 0)) {
				connectButton.setEnabled(false);
				try {
					mrGUI.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
					mailClient = new Pop3(hostTextField.getText());
					clientTextArea.append(mailClient.getWelcome() + "\n");
					clientTextArea.append(mailClient.user(userTextField.getText()) + "\n");
					clientTextArea.append(mailClient.pass(userPasswordField.getText())+ "\n");							
					mailCount = mailClient.getMailCount();
					mrGUI.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));

					// If Mailbox is empty then do nothing.
					if(mailCount == 0) {
						JOptionPane.showMessageDialog(null, "The mailbox is empty!", "Information", JOptionPane.INFORMATION_MESSAGE);
						mailClient.quit();
						connectButton.setEnabled(true);
						return;
					}

					// Retrive user input
					do {					
						String inputValue = JOptionPane.showInputDialog(
								"There are " + mailCount + " mail(s) on server, how much you would like to delete?", mailCount);

						// If user press cancel button then do nothing.
						if(inputValue == null) {
							connectButton.setEnabled(true);
							return;
							// Check data validity
						} else if(inputValue.length() > 0) {
							try {
								delMail = Integer.parseInt(inputValue);
							}
							catch(NumberFormatException ex) {
								JOptionPane.showMessageDialog(
										null, "The specified number is out of range.", "Warning", JOptionPane.WARNING_MESSAGE);
								continue;
							}
						}
						if((delMail <= 0) || (delMail > mailCount)) {
							JOptionPane.showMessageDialog(
									null, "The specified number is out of range.", "Warning", JOptionPane.WARNING_MESSAGE);
							continue;
						}
						getInput = false;
					} while(getInput == true);
				}

				catch(Pop3Exception e) { 
					clientTextArea.append("Error: " + e.getMessage() + "\n");
					mrGUI.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
					connectButton.setEnabled(true);
					return;
				}

				// Processing indicator
				m_progress = new ProgressMonitor(mrGUI,
						"Processing","", 0, 100);
				m_progress.setMinimum(1);
				m_progress.setMaximum(delMail);
				Thread runner = new Thread(new Runnable() {
					int m_counter;

					public void run() {
						try {
							for(m_counter = 1; m_counter <= delMail && !m_progress.isCanceled(); m_counter++) {
								mailClient.dele(m_counter);
								m_progress.setProgress(m_counter);
								try {
									Thread.sleep(1);
								}
								catch(InterruptedException ignore) {}									

								// Task canceled
								if(m_progress.isCanceled()) {
									mailClient.disconnect();
									clientTextArea.append("Canceled\n");
									connectButton.setEnabled(true);
									return;
								}
							}
							try {
								mailClient.quit();	
							}
							catch(Pop3Exception ignore) {}
							clientTextArea.append("Done\n");
							connectButton.setEnabled(true);
						}
						catch(Pop3Exception e) {
							clientTextArea.append("Error: " + e.getMessage() + "\n");
							try {
								mailClient.quit();
							}
							catch (Pop3Exception ignore) {}
						}
					}
				});
				runner.start();
			}
		}
	}

	/*
	 * Create the GUI and show it. As with all GUI code, this must run
	 * on the event-dispatching thread.
	 */

	public mailRemoverGUI() {
		init();
		northPanel.add(hostLabel);
		northPanel.add(hostTextField);
		northPanel.add(usernameLabel);
		northPanel.add(userTextField);	
		northPanel.add(passwordLabel);		
		northPanel.add(userPasswordField);

		//Lay out the panel.
		SpringUtilities.makeCompactGrid(northPanel,
				3, 2, //rows, cols
				6, 6,        //initX, initY
				6, 6);       //xPad, yPad

		add(northPanel, BorderLayout.NORTH); 
		add(scrollArea, BorderLayout.CENTER);
		add(connectButton, BorderLayout.SOUTH); 

		setVisible(true);
		userTextField.requestFocus();
	}

	public void init() {
		mrGUI = this;

		northPanel = new JPanel(new SpringLayout()); 

		hostLabel = new JLabel("Host:");
		usernameLabel = new JLabel("Username:");
		passwordLabel = new JLabel("Password:"); 

		hostTextField = new JTextField("htctaomsg2.htc.com.tw");				
		userTextField = new JTextField();
		userTextField.setSize(150, 20);				

		userPasswordField = new JPasswordField();
		userPasswordField.setSize(150, 20); 

		connectButton = new JButton("Connect");
		connectButton.addActionListener(new connectPressed());

		clientTextArea = new JTextArea();
		clientTextArea.setEditable(false);
		scrollArea = new JScrollPane(clientTextArea);
		scrollArea.setSize(230, 200);

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(260, 400);
		setTitle("Mail Remover " + VERSION);
		setMinimumSize(new Dimension(260, 400));
		setLocationRelativeTo(null);
		getRootPane().setDefaultButton(connectButton);
	}
}
